/**
 * 
 */
package com.huniu.links;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;
import java.util.GregorianCalendar;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

import com.huniu.links.exception.LinkProcessException;
import com.huniu.links.model.SeedXMLProperty;
import com.huniu.utility.DateUtil;

/**
 * @author zandy (chenheng)
 * 
 */
public class LinkSeedProcessImpl implements ILinkSeedProcess {

	public String generateSeedFile(String parentFolder, String urls)
			throws LinkProcessException {
		String file = generateSeedFolder(parentFolder);
		return generateSeedFile(file, urls.split(","));
	}

	private String generateSeedFile(String fileName, String[] urls)
			throws LinkProcessException {
		Document document = DocumentHelper.createDocument();
		Element root = document.addElement(SeedXMLProperty.ROOT);
		for (String url : urls) {
			root.addElement(SeedXMLProperty.ELEMENT).addText(url);
		}
		try {
			OutputFormat format = OutputFormat.createPrettyPrint();
			XMLWriter writer = new XMLWriter(new FileWriter(new File(fileName)),format);
			writer.write(document);
			writer.close();
		} catch (IOException e) {
			throw new LinkProcessException("Write XML document failure", e);
		}
		return document.asXML();
	}

	private String generateSeedFolder(String parentFolder) throws LinkProcessException {
		GregorianCalendar calender = new GregorianCalendar();
		Date currentDate = calender.getTime();
		String childFolder = DateUtil.convertDateToString(currentDate,
				DateUtil.DATE_FORMAT_1);
		String folder = parentFolder + File.separator + childFolder;
		File file = new File(folder);
		if (!file.exists()) {
			file.mkdirs();
		}
		String fileName = DateUtil.convertDateToString(currentDate,
				DateUtil.DATE_FORMAT_2);
		String filePath = folder + File.separator + fileName + SeedXMLProperty.EXTENSION ;
		return filePath ;
	}
}
